'use client';

import { useEffect, useState } from 'react';

export default function WasmPage() {
  const [result, setResult] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function loadWasm() {
      try {
        const response = await fetch('/wasm/add.wasm');
        if (!response.ok) {
          throw new Error(`Failed to fetch wasm module: ${response.statusText}`);
        }
        const buffer = await response.arrayBuffer();
        const module = await WebAssembly.instantiate(buffer);
        const add = module.instance.exports.add as (a: number, b: number) => number;
        const sum = add(5, 7);
        setResult(sum);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An unknown error occurred');
        console.error(err);
      }
    }

    loadWasm();
  }, []);

  return (
    <div style={{ padding: '2rem' }}>
      <h1>Simple WASM Example</h1>
      <p>This page loads a WebAssembly module to perform an addition.</p>
      <div>
        {error && <p style={{ color: 'red' }}>Error: {error}</p>}
        {result !== null ? (
          <p>
            The result of calling the wasm <code>add(5, 7)</code> function is: <strong>{result}</strong>
          </p>
        ) : (
          <p>Loading wasm module and calculating...</p>
        )}
      </div>
      <p>
        Check the browser console and network tab to see the <code>add.wasm</code> file being loaded.
      </p>
    </div>
  );
}
